<?php
// +----------------------------------------------------------------------
// | Scallion 
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.scallion.top All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Liuxg < 420695648@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
class WxviewController extends HomeBaseController
{
	public function mobile_bind_wx(){
		if(cmf_is_wechat()){
			return $this->fetch();
		}
		else{
			$this->error('请在微信公众号中访问！',url('portal/index/index'));
		}
	}
	
	public function wx_bind_redirect(){
		if(cmf_is_wechat()){
			if($this->request->param()){
				$param = $this->request->param();
				$state = $param['state'];
				if(!$state){
					$this->error('非法访问！',url('portal/index/index'));
				}
				else{
					$wx = new \wechatcontroller;
					$res = $wx->getOauthAccessToken($param['code']);
					$data['openid'] = $res['openid'];
					$data['id'] = $state;
					$is_bind = db('third_party_user')->where(['openid'=>$data['openid'],'status'=>'1'])->find();
					if($is_bind){
						$this->wx_login_do($state);
						$this->error('您已经成功绑定！',url('portal/wxview/wx_index',['state'=>'user_center']));
					}
					else{
						$bind = new \app\portal\controller\CommonController;
						$bind_res = $bind->bind_wx($data);
						if($bind_res>0){
							$this->wx_login_do($state);
							$this->success('绑定成功',url('portal/wxview/user_center'));
						}
						else{
							switch($bind_res){
								case '-1':
									$this->error('该用户已绑定微信，请解绑后操作！',url('portal/index/index'));
									break;
								case '-2':
									$this->error('该微信已绑定其他用户'.$is_bind_user['nickname'].',请解绑后操作！',url('portal/index/index'));
									break;
								case '-4':
									$this->error('用户已被封禁！',url('portal/index/index'));
									break;
								case '-5':
									$this->error('用户不存在',url('portal/index/index'));
									break;
								default:
									$this->error('绑定失败！',url('portal/index/index'));
							}
						}
					}
				}
			}
			else{
				$this->error('非法访问！',url('portal/index/index'));
			}
		}
		else{
			$this->error('请在微信公众号中访问！',url('portal/index/index'));
		}
	}
	
	public function mobile_bind_wx_do(){
		if(cmf_is_wechat()){
			if($this->request->param()){
				$param = $this->request->param();
				$captcha = cmf_captcha_check($param['captcha']);
				if($captcha){
					$passwordInDb = db('user')
					->where(['user_login'=>$param['username']])
					->whereOr(['user_email'=>$param['username']])
					->whereOr(['mobile'=>$param['username']])
					->field('user_pass,id')->find();
					if($passwordInDb){
						if(cmf_compare_password($param['password'],$passwordInDb['user_pass'])){
							$wx = new \wechatcontroller;
							$scope = 'snsapi_base';
							$callback = url('portal/wxview/wx_bind_redirect','','',true);
							$state = $passwordInDb['id'];
							$url = $wx->getOauthRedirect($callback,$state,$scope);
							$this->redirect($url);
						}
						else{
							$this->error('密码错误！');
						}
					}
					else{
						$this->error('用户不存在！');
					}
				}
				else{
					$this->error('验证码错误');
				}
			}
			else{
				$this->error('非法访问！1',url('portal/index/index'));
			}
		}
		else{
			$this->error('请在微信公众号中访问！',url('portal/index/index'));
		}
	}
	
	public function user_center(){
		if(cmf_is_wechat()){
			if(cmf_get_current_admin_id()){
				$param = cmf_get_current_admin_id();
				$user = db('user')->where(['id'=>$param,'user_status'=>'1'])->field('avatar')->find();
				$avatar = cmf_get_user_avatar_url($user['avatar']);
				$this->assign('avatar',$avatar);
				return $this->fetch();
			}
			else{
				$this->error('非法访问！',url('portal/index/index'));
			}
		}
		else{
			$this->error('请在微信公众号中访问！',url('portal/index/index'));
		}
	}

	public function get_timetable(){
		if($this->request->param()){
			$param = $this->request->param();
			$user = db('user')->where(['id'=>$param['id'],'user_status'=>'1'])->find();
			if($user){
				$teacher = db('teacher')->where(['union_id'=>$user['id']])->find();
				$data = db('class_timetable')
				->where(['teacher_id'=>$teacher['id']])
				->alias('a')
				->join('class b','a.class_id = b.id')
				->join('classroom c','a.classroom_id = c.id')
				->field('b.name as class_name,c.name as classroom_name,a.class_number as class_number,a.times as times,start_time,end_time')
				->order('start_time asc')
				->select()->toarray();
				$assign_data = '';
				$date = '';
				$i = 0;
				foreach($data as $vo){
					if($date == date('Y-n-j',$vo['start_time'])){
						$i++;
						$assign_data[$date][$i]['title'] = '班级：'.$vo['class_name'].'</br>教室：'.$vo['classroom_name'].'</br>第'.$vo['times'].'/'.$vo['class_number'].'次课';
						$assign_data[$date][$i]['startTime'] = date('Y年n月j日 H:i',$vo['start_time']);
						$assign_data[$date][$i]['endTime'] = date('Y年n月j日 H:i',$vo['end_time']);
					}
					else{
						$date = date('Y-n-j',$vo['start_time']);
						$i = 0;
						$assign_data[$date][$i]['title'] = '班级：'.$vo['class_name'].'</br>教室：'.$vo['classroom_name'].'</br>第'.$vo['times'].'/'.$vo['class_number'].'次课';
						$assign_data[$date][$i]['startTime'] = date('Y年n月j日 H:i',$vo['start_time']);
						$assign_data[$date][$i]['endTime'] = date('Y年n月j日 H:i',$vo['end_time']);
					}
				}
				if(cmf_is_mobile()){
					$safe_url['user_name'] = $user['user_nickname'];
					$safe_url['timetable_data'] = json_encode($assign_data);
					$surl = new SurlController;
					$encode = $surl->encode('wxview/get_timetable_mobile','safe_url',$safe_url);
					$this->redirect($encode,302);
				}
				else{
					$safe_url['user_name'] = $user['user_nickname'];
					$safe_url['timetable_data'] = json_encode($assign_data);
					$surl = new SurlController;
					$encode = $surl->encode('wxview/get_timetable_mobile','safe_url',$safe_url);
					$this->redirect($encode,302);
					// return $this->fetch();
					// $this->assign('user_name',$user['user_nickname']);
					// $this->assign('timetable_data',json_encode($assign_data));
					// return $this->fetch();
				}
			}
			else{
				$this->error('账号已被禁用！',url('portal/index/index'));
			}
		}
		else{
			$this->error('非法访问！',url('portal/index/index'));
		}
	}
	
	public function index(){
		return 'what do you want to do ?';
	}
	
	public function wx_index(){
		if(cmf_is_wechat()){
			if($this->request->param()){
				$param = $this->request->param();
				if(isset($param['state'])){
					$state = $param['state'];
				}
				else{
					$this->error('非法访问！',url('portal/index/index'));
				}
			}
			else{
				$this->error('非法访问！',url('portal/wxview/index'));
			}
			if($is_login = cmf_get_current_admin_id()){
				$url = url('portal/wxview/'.$state,['id'=>$is_login],'',true);
				$this->redirect($url);
			}
			else{
				$scope = 'snsapi_base';
				$callback = url('portal/wxview/wx_redirect','','',true);
				$wx = new \wechatcontroller;
				$url = $wx->getOauthRedirect($callback,$state,$scope);
				$this->redirect($url);
			}
		}
		else{
			$this->error('请在微信浏览器中访问！',url('portal/index/index'));
		}
	}
	
	public function wx_login_do($param){
		$where['id'] = $param;
		$result = db('user')->where($where)->find();

        if (!empty($result) && $result['user_type'] == 1) {
			$groups = db('RoleUser')
				->alias("a")
				->join('__ROLE__ b', 'a.role_id =b.id')
				->where(["user_id" => $result["id"], "status" => 1])
				->value("role_id");
			if ($result["id"] != 1 && (empty($groups) || empty($result['user_status']))) {
				return false;
			}
			//登入成功页面跳转
			session('ADMIN_ID', $result["id"]);
			session('name', $result["user_login"]);
			$result['last_login_ip']   = get_client_ip(0, true);
			$result['last_login_time'] = time();
			$token                     = cmf_generate_user_token($result["id"], 'wechat');
			if (!empty($token)) {
				session('token', $token);
			}
			db('user')->update($result);
			cookie("admin_username", $result['user_login'], 3600 * 24 * 30);
			session("__LOGIN_BY_CMF_ADMIN_PW__", null);
			return true;
        } else {
            return false;
        }
	}
	
	public function wx_redirect(){
		if(cmf_is_wechat()){
			if($this->request->param()){
				$param = $this->request->param();
				$state = $param['state'];
				if(!$state){
					$this->error('非法访问！',url('portal/index/index'));
				}
				else{
					$user = $this->get_user();
					if($user){
						$this->wx_login_do($user['id']);
						$url = url('portal/wxview/'.$state,['id'=>$user['id']],'',true);
						$this->redirect($url);
					}
					else{
						$this->error('请绑定微信后操作！',url('portal/wxview/mobile_bind_wx'));
					}
				}
			}
			else{
				$this->error('非法访问！',url('portal/index/index'));
			}
		}
		else{
			$this->error('请在微信公众号中访问！',url('portal/index/index'));
		}
	}
	
	public function get_user(){
		$wx = new \wechatcontroller;
		$res = $wx->getOauthAccessToken();
		$openid = $res['openid'];
		$is_bind = db('third_party_user')->where(['openid'=>$openid,'status'=>'1'])->find();
		if($is_bind){
			$user = db('user')->where(['id'=>$is_bind['user_id'],'user_status'=>'1'])->find();
			return($user);
		}
		else{
			return false;
		}
	}
}